package org.xxpay.pay.channel.witbytespay;

import com.alipay.api.internal.util.codec.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.xxpay.core.common.util.MD5Util;
import org.xxpay.core.common.util.MyLog;
import org.xxpay.pay.channel.saaspay.SaaspayConfig;
import org.xxpay.pay.channel.saaspay.SaaspayUtil;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;

/**
 *
 *<p>工具类</p>
 * @author  NOT-FIND
 * @version 2018年7月19日 NOT-FIND
 */
public class WitbytespayUtil {
    private static String encodingCharset = "UTF-8";
    private static final MyLog _log = MyLog.getLog(WitbytespayUtil.class);

    /**
     * H5PAY配置
     */
    public static class H5PayBody{
        //商户编号
        String merchant_id;
        //支付金额
        String amount;
        //会员账号
        String userid;
        //订单编号
        String ordercode;
        //支付方式
        String paytool;
        //支付通道
        String pay_method;
        //回调地址
        String callback;
        //交易时间(时间戳)
        String timestamp;
        //交易IP地址
        String trade_ip;
        //成功地址
        String success_url;
        //失败地址
        String fail_url;
        //商品名字
        String goods_name;
        //商品描述
        String goods_desc;
        //微信平台 openid
        String openid;
        //授权编码
        String authcode;
        //交易签名
        String sign;

        String toJson(){
            StringBuilder sb = new StringBuilder();
            sb.append("{");
            if (this.merchant_id != null) sb.append("\"merchant_id\":\"" + this.merchant_id + "\",");
            if (this.amount != null) sb.append("\"amount\":\"" + this.amount + "\",");
            if (this.userid != null) sb.append("\"userid\":\"" + this.userid + "\",");
            if (this.ordercode != null) sb.append("\"ordercode\":\"" + this.ordercode + "\",");
            if (this.paytool != null) sb.append("\"paytool\":\"" + this.paytool + "\",");
            if (this.pay_method != null) sb.append("\"pay_method\":\"" + this.pay_method + "\",");
            if (this.callback != null) sb.append("\"callback\":\"" + this.callback + "\",");
            if (this.timestamp != null) sb.append("\"timestamp\":\"" + this.timestamp + "\",");
            if (this.trade_ip != null) sb.append("\"trade_ip\":\"" + this.trade_ip + "\",");
            if (this.success_url != null) sb.append("\"success_url\":\"" + this.success_url + "\",");
            if (this.fail_url != null) sb.append("\"fail_url\":\"" + this.fail_url + "\",");
            if (this.goods_name != null) sb.append("\"goods_name\":\"" + this.goods_name + "\",");
            if (this.goods_desc != null) sb.append("\"goods_desc\":\"" + this.goods_desc + "\",");
            if (this.openid != null) sb.append("\"openid\":\"" + this.openid + "\",");
            if (this.authcode != null) sb.append("\"authcode\":\"" + this.authcode + "\",");
            if (this.sign != null) sb.append("\"sign\":\"" + this.sign + "\",");
            if (sb.charAt(sb.length() - 1) == ',')
                sb.deleteCharAt(sb.length() - 1);
            sb.append("}");
            return sb.toString();
        }

        @Override
        public String toString(){
            return this.toJson();
        }
    }


    /**
     * 发送httpGET请求
     * @param url 请求url
     * @return response
     */
    public static String h5Request(String url,String reqBody){
        String response = "";
        PrintWriter out = null;
        BufferedReader in = null;
        try{
            URL realUrl = new URL(url);
            URLConnection conn = realUrl.openConnection();
            HttpURLConnection httpUrlConnection = (HttpURLConnection) conn;
            httpUrlConnection.setRequestProperty("Content-Type", "application/json");
            httpUrlConnection.setDoOutput(true);
            httpUrlConnection.setDoInput(true);
            out = new PrintWriter(httpUrlConnection.getOutputStream());
            out.write(reqBody);
            out.flush();
            httpUrlConnection.connect();
            in = new BufferedReader(new InputStreamReader(httpUrlConnection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                response += line;
            }
        }catch(Exception e){
            e.printStackTrace();
        } finally {
            try {
                if (out != null) { out.close();}
                if (in != null) {in.close();}
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return response;
    }


    /**
     * 获取签名头
     * @param body 请求体
     * @return authorization 认证报文
     * @throws Exception
     */
    public static String getSignatureByMD5(String body,String secret) throws Exception {
        WitbytespayConfig witbytespayConfig = new WitbytespayConfig();
        String sign_tmp = body+"&secret="+secret;
        String localSignatureStr = MD5Util.string2MD5(sign_tmp).toUpperCase();
        return localSignatureStr;
    }

    public static String generateSHA256Signature(String data) {
        StringBuilder hexString = new StringBuilder();
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            _log.info("待签名串：{}",data);
            byte[] hash = digest.digest(data.getBytes());
            for (byte b : hash) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
        }catch (Exception e){
            _log.error("签名错误：{},{}",e.getMessage(),e.getCause());
        }
        return hexString.toString();
    }

    /**
     * 查询参数
     */
    public static class QueryBody{
        //订单编号
        String ordercode;
        //商户编号
        String merchant_id;
        //时间戳
        String timestamp;
        //查询签名
        String sign;

        String toJson(){
            StringBuilder sb = new StringBuilder();
            sb.append("{");
            if (this.ordercode != null) sb.append("\"ordercode\":\"" + this.ordercode + "\",");
            if (this.merchant_id != null) sb.append("\"merchant_id\":\"" + this.merchant_id + "\",");
            if (this.timestamp != null) sb.append("\"timestamp\":\"" + this.timestamp + "\",");
            if (this.sign != null) sb.append("\"sign\":\"" + this.sign + "\",");
            if (sb.charAt(sb.length() - 1) == ',')
                sb.deleteCharAt(sb.length() - 1);
            sb.append("}");
            return sb.toString();
        }
        public String toString(){
            return this.toJson();
        }
    }


    /**
     * 查询发送http请求
     * @param url 请求url
     * @param reqBody  请求体
     * @return response
     */
    static String queryRequest(String url, String reqBody){
        String response = "";
        PrintWriter out = null;
        BufferedReader in = null;
        try{
            URL realUrl = new URL(url);
            URLConnection conn = realUrl.openConnection();
            HttpURLConnection httpUrlConnection = (HttpURLConnection) conn;
            httpUrlConnection.setRequestProperty("Content-Type", "application/json");
            httpUrlConnection.setDoOutput(true);
            httpUrlConnection.setDoInput(true);
            out = new PrintWriter(httpUrlConnection.getOutputStream());
            out.write(reqBody);
            out.flush();
            httpUrlConnection.connect();
            in = new BufferedReader(new InputStreamReader(httpUrlConnection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                response += line;
            }
        }catch(Exception e){
            e.printStackTrace();
        } finally {
            try {
                if (out != null) { out.close();}
                if (in != null) {in.close();}
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return response;
    }


    public static class H5PayRefundBody{
        //商户编号
        String merchant_id;
        //交易时间
        String timestamp;
        //退款编号
        String refund_code;
        //订单编号
        String ordercode;
        //交易金额
        String amount;
        //请求签名
        String sign;


        String toJson(){
            StringBuilder sb = new StringBuilder();
            sb.append("{");
            if (this.merchant_id != null) sb.append("\"merchant_id\":\"" + this.merchant_id + "\",");
            if (this.timestamp != null) sb.append("\"timestamp\":\"" + this.timestamp + "\",");
            if (this.refund_code != null) sb.append("\"refund_code\":\"" + this.refund_code + "\",");
            if (this.ordercode != null) sb.append("\"ordercode\":\"" + this.ordercode + "\",");
            if (this.amount != null) sb.append("\"amount\":\"" + this.amount + "\",");
            if (this.sign != null) sb.append("\"sign\":\"" + this.sign + "\",");

            if (sb.charAt(sb.length() - 1) == ',')
                sb.deleteCharAt(sb.length() - 1);
            sb.append("}");
            return sb.toString();
        }
        public String toString(){
            return this.toJson();
        }
    }

    /**
     * 查询发送post请求
     * @param url 请求url
     * @param authorization 认证报文
     * @param reqBody  请求体
     * @return response
     */
    static String refundRequest(String url, String reqBody){
        String response = "";
        PrintWriter out = null;
        BufferedReader in = null;
        try{
            URL realUrl = new URL(url);
            URLConnection conn = realUrl.openConnection();
            HttpURLConnection httpUrlConnection = (HttpURLConnection) conn;
            httpUrlConnection.setRequestProperty("Content-Type", "application/json");
            httpUrlConnection.setDoOutput(true);
            httpUrlConnection.setDoInput(true);
            out = new PrintWriter(httpUrlConnection.getOutputStream());
            out.write(reqBody);
            out.flush();
            httpUrlConnection.connect();
            in = new BufferedReader(new InputStreamReader(httpUrlConnection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                response += line;
            }
        }catch(Exception e){
            e.printStackTrace();
        } finally {
            try {
                if (out != null) { out.close();}
                if (in != null) {in.close();}
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return response;
    }
}
